#!/bin/bash
#Created by Kris Occhipinti Copyright 2018
#http://filmsbykris.com
#Licensed under AGPL - https://www.gnu.org/licenses/agpl-3.0.txt

func="$1"
ip="<scanner IP Address>"
port="9999"
knownURL="<URL for Known Device List>"
tmp="/tmp/maclog.tmp"
log=""

function main(){
  if [ "$func" = "known" ]
  then
    listKnown
  elif [ "$func" = "help" ]
  then
    help
  elif [ "$func" = "all" ]
  then
    all
  elif [ "$func" = "devices" ]
  then
    deviceOnly
  else
    recent
  fi
}

function recent(){
  wget -qO "$tmp" "http://$ip:$port$(getLast 1)"
  getKnown 
}

function all(){
  rm "$tmp"
  echo -n "Getting all logs..."
  wget -qO- "http://$ip:$port"|\
    sed 's/<a/\n<a/g'|\
    grep href|\
    grep csv|\
    cut -d\' -f2|while read line
    do
      echo -n "."
      wget -qO- "http://$ip:$port$line" >> $tmp
    done

  echo ""
  getKnown 
}

function getKnown(){
  wget "$knownURL" -qO-|\
    tr '[:lower:]' '[:upper:]'|\
    awk '{print $1 " " $3}'|while read line
    do
      set -- $line
      #sed -i "s/$2/\\\e[7m$1\\\e[39m/g" "$tmp"
      sed -i "s/$2/\\\e[7m$1\\\e[0m/g" "$tmp"
    done

    echo -e "$(cat "$tmp")"
}

function listKnown(){
  echo "Known from $knownURL"
  echo ""
  wget "$knownURL" -qO-
}

function getLast(){
  wget -qO- "http://$ip:$port"|\
    sed 's/<a/\n<a/g'|\
    grep href|\
    grep csv|\
    cut -d\' -f2|\
    tail -n $1
}

function deviceOnly(){
  wget -qO- "http://$ip:$port$(getLast 1)"|\
    tr " " "\n"|\
    grep -i '[0-9A-F]\{2\}\(:[0-9A-F]\{2\}\)\{5\}'|\
    sort -u > "$tmp"
  getKnown
}

function help(){
  echo "Usage:"
  echo "$0  --  DEFAULT-View most recent logs."
  echo "$0 known  --  LIST know devices"
  echo "$0 all  --  LIST all logs"
  echo "$0 devices  --  LIST Device MAC/Names Only"
}

main